package flexconsole.controller {
	import flash.filesystem.File;
	
	import flexconsole.AppFacade;
	import flexconsole.ConfigKeys;
	import flexconsole.model.*;
	import flexconsole.utils.FileUtil;
	import flexconsole.view.AppMediator;
	
	import flexunit.framework.Assert;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	/**
	 * Startup command for the application.
	 * @author ivanchoo
	 *
	 */
	public class StartUpCommand extends SimpleCommand {
		
		static private var logger:ILogger = Log.getLogger("flexconsole.controller.StartUpCommand");
		
		override public function execute(notification:INotification):void {
			logger.debug("execute({0})", notification);
			super.execute(notification);
			
			try {
				var app:FlexConsole = notification.getBody() as FlexConsole;
				Assert.assertNotNull(app);
				
				var appFacade:AppFacade = facade as AppFacade;
				
				//   Register commands
                appFacade.registerCommand(AppFacade.SHUTDOWN, ShutdownCommand);
                appFacade.registerCommand(AppFacade.CONNECTION, ConnectionCommand);
                appFacade.registerCommand(AppFacade.CHECK_APP_UPDATE, CheckAppUpdateCommand);
                appFacade.registerCommand(AppFacade.HELP, HelpCommand);
				
				//  Register proxies
				appFacade.registerProxy(new ConfigProxy(AppFacade.PROXYNAME_CONFIG));
                appFacade.registerProxy(new CategoryProxy(AppFacade.PROXYNAME_CATEGORY));
                appFacade.registerProxy(new LogMessageProxy(AppFacade.PROXYNAME_LOG_MESSAGE));
				
				//  Register views
				appFacade.registerMediator(new AppMediator(AppFacade.MEDIATORNAME_APP, app));
				
				//  Startup sequence
				appFacade.configProxy.source = FileUtil.readFileAsXML(getFile(AppFacade.FILENAME_CONFIG));
                appFacade.categoryProxy.source = FileUtil.readFileAsXML(getFile(AppFacade.FILENAME_CATEGORY));
                appFacade.logMessageProxy.source = FileUtil.readFileAsXML(getFile(AppFacade.FILENAME_LOG));
				
				sendNotification(AppFacade.CONNECTION, appFacade.configProxy.getValue(ConfigKeys.CONNECTED, true));
				if (appFacade.configProxy.getValue(ConfigKeys.CHECK_UPDATE_ON_STARTUP, true)) {
					sendNotification(AppFacade.CHECK_APP_UPDATE);
				}
				
			} catch (e:Error) {
				logger.error(e.message);
				throw e;
			}
		}
		
		protected function getFile(path:String):File {
			Assert.assertNotNull(path);
			return File.applicationStorageDirectory.resolvePath(path);
		}
	
	}
}